<template>
  <a-form :label-col="{span: 6}" :wrapper-col="{span: 16}">
    <a-form-item label="部门名称" v-bind="validateInfos.name">
      <a-input v-model:value="modelRef.name" v-focus />
    </a-form-item>
    <a-form-item label="上级部门" v-bind="validateInfos.parentCodePath">
      <a-cascader v-model:value="modelRef.parentCodePath" :options="treeData" :fieldNames="{label: 'name', value: 'code', children: 'children' }" changeOnSelect expandTrigger="hover">
        <template #displayRender="{labels, selectedOptions}">
          <span>{{labels[labels.length-1]}}</span>
        </template>
      </a-cascader>
    </a-form-item>

    <a-form-item :wrapper-col="{ span: 14, offset: 6 }">
      <a-space>
        <a-button @click="resetFields">重置</a-button>
        <a-button type="primary" @click.prevent="onSubmit">保存</a-button>
      </a-space>
    </a-form-item>
  </a-form>
</template>
<script>
import { insert, update, tree } from "@/api/sysDeptApi.ts";
import { defineComponent, reactive, toRefs, toRaw, onMounted } from "vue";
import { Form, message } from "ant-design-vue";
const useForm = Form.useForm;
export default defineComponent({
  props: {
    type: String,
    row: Object
  },
  setup(props, context) {
    const { type, row } = props;
    const data = reactive({
      treeData: []
    });
    const modelRef = reactive({
      name: row?.name,
      parentCodePath: row?.parentCodePath?.split(",")
    });
    const rulesRef = reactive({
      name: [
        {
          required: true,
          message: "部门名称必填项"
        }
      ],
      parentCodePath: [
        {
          required: true,
          message: "上级部门必填项"
        }
      ]
    });
    const { resetFields, validate, validateInfos } = useForm(
      modelRef,
      rulesRef
    );

    const onSubmit = () => {
      validate()
        .then(() => {
          if (type == "insert") {
            insertData();
          } else if (type == "update") {
            updateData();
          }
        })
        .catch(err => {
          console.log("error", err);
        });
    };

    const initTreeData = () => {
      let params = {};
      tree(params).then(resd => {
        if (row) {
          let currentCode = row.code;

          let recursion = detpChild => {
            console.log(detpChild);
            // 处理数据
            detpChild.map(dept => {
              // 判断 所选择的部门不能是当前部门和子部门
              if (dept.code == currentCode) dept.disabled = true;
              if (dept.children) recursion(dept.children);
            });
          };
          // 处理数据
          recursion(resd);
        }

        data.treeData = [{ code: "root", name: "根部门", children: resd }];
      });
    };
    // 页面初始化
    onMounted(() => {
      initTreeData(); // 初始化树
    });

    const insertData = () => {
      let form = toRaw(modelRef);
      let params = {
        name: form.name,
        parentCode: form.parentCodePath[form.parentCodePath.length - 1],
        parentCodePath: form.parentCodePath.join(",")
      };
      insert(params).then(resd => {
        message.success("创建成功");
        context.emit("success", resd);
      });
    };

    const updateData = () => {
      let form = toRaw(modelRef);
      let params = {
        id: row.id,
        name: form.name,
        parentCode: form.parentCodePath[form.parentCodePath.length - 1],
        parentCodePath: form.parentCodePath.join(",")
      };
      update(params).then(resd => {
        message.success("更新成功");
        context.emit("success", resd);
      });
    };

    return {
      ...toRefs(data),
      validateInfos,
      resetFields,
      modelRef,
      onSubmit
    };
  }
});
</script>